package com.lsh.netty.http.xml;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelFutureListener;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.Future;
import io.netty.util.concurrent.GenericFutureListener;

import java.util.ArrayList;
import java.util.List;

/**
 * @author ：LiuShihao
 * @date ：Created in 2021/6/8 9:06 下午
 * @desc ：服务端业务处理类
 */
public class HttpXmlServerHandler extends SimpleChannelInboundHandler<HttpXmlRequest> {
    @Override
    protected void messageReceived(final ChannelHandlerContext ctx, HttpXmlRequest xmlRequest) throws Exception {
        HttpRequest request = xmlRequest.getRequest();
        Order order = (Order) xmlRequest.getBody();
        // 输出解码获得的Order对象
        System.out.println("服务器收到的请求: " + order);
        dobusiness(order);
//        System.out.println(order);
        ChannelFuture future = ctx.writeAndFlush(new HttpXmlResponse(null, order));
        if (request.headers().get(HttpHeaderNames.CONNECTION) != HttpHeaderValues.KEEP_ALIVE) {
            future.addListener(new GenericFutureListener<Future<? super Void>>() {
                @Override
                public void operationComplete(Future future) throws Exception {
                    ctx.close();
                }
            });
        }

    }
    private void dobusiness(Order order) {
        order.getCustomer().setXing("狄");
        order.getCustomer().setName("仁杰");
        List<String> midNames = new ArrayList<String>();
        midNames.add("李元芳");
        order.getCustomer().setCustFullName(midNames);
        Address address = order.getBillAddress();
        address.setCity("洛阳");
        address.setCountry("大唐");
        address.setStreet1("河南道");
        address.setPostCode("123456");
        order.setAddress(address);
        order.setBillAddress(address);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        System.out.println("服务端处理类");
        // 在链路没有关闭并且出现异常的时候发送给客户端错误信息
        if (ctx.channel().isActive()) {
            System.out.println("链路没有关闭并且出现异常的时候发送给客户端错误信息");
            sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR);
        }
    }

    private static void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) {
        FullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, status,
                Unpooled.copiedBuffer("失败: " + status.toString() + "\r\n", CharsetUtil.UTF_8));
        response.headers().set(org.springframework.http.HttpHeaders.CONTENT_TYPE, "text/plain; charset=UTF-8");
        ctx.writeAndFlush(response).addListener(ChannelFutureListener.CLOSE);
    }

}
